package org.example.myleet.p735;

import java.util.Deque;
import java.util.LinkedList;

public class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        Deque<Integer> stack = new LinkedList<>();
        for (int asteroid : asteroids) {
            if (stack.isEmpty()) {
                stack.push(asteroid);
            } else {
                Integer top = stack.peek();
                if (!willCollide(top, asteroid)) {
                    stack.push(asteroid);
                } else {
                    boolean asteroidDestroyed = false;
                    while (willCollide(top, asteroid)) {
                        int topMass = Math.abs(top);
                        int asteroidMass = Math.abs(asteroid);
                        if (topMass > asteroidMass) {
                            asteroidDestroyed = true;
                            break;
                        }
                        if (topMass == asteroidMass) {
                            stack.pop();
                            asteroidDestroyed = true;
                            break;
                        }
                        stack.pop();
                        if (stack.isEmpty()) {
                            break;
                        }
                        top = stack.peek();
                    }
                    if (!asteroidDestroyed) {
                        stack.push(asteroid);
                    }
                }
            }
        }
        int[] res = new int[stack.size()];
        int i = stack.size() - 1;
        while (!stack.isEmpty()) {
            res[i--] = stack.pop();
        }
        return res;
    }

    private boolean willCollide(int asteroid1, int asteroid2) {
        return asteroid1 > 0 && asteroid2 < 0;
    }
}
